<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>翻译工具配置中心</title>
  <!-- 引入Vue.js -->
  <script src=" https://fastly.jsdelivr.net/npm/vue@2.6.14/dist/vue.js "></script>
  <!-- 引入Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- 引入Font Awesome -->
  <link href="https://fastly.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义颜色和字体 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#3B82F6',
            secondary: '#10B981',
            neutral: '#64748B',
            dark: '#1E293B',
            light: '#F8FAFC',
            success: '#10B981',
            warning: '#F59E0B',
            error: '#EF4444'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .input-focus {
        @apply focus:ring-2 focus:ring-primary/50 focus:border-primary focus:outline-none;
      }
      .tab-active {
        @apply border-primary text-primary font-medium;
      }
      /* 开关按钮样式 */
      .toggle-checkbox:checked {
        right: 0;
        border-color: #68D391;
      }
      .toggle-checkbox:checked + .toggle-label {
        background-color: #68D391;
      }
      /* 信息提示框样式 */
      .info-box {
        @apply bg-gray-50 border border-gray-200 rounded-lg p-4 my-6 text-sm;
      }
      /* 结果展示框样式 */
      .result-box {
        @apply bg-gray-50 border border-gray-200 rounded-xl h-full flex flex-col;
      }
      /* 实时输出区域 - 优化滚动 */
      .result-content {
        @apply flex-1 overflow-y-auto p-4 text-sm font-mono bg-gray-900 text-gray-100 rounded-lg;
        max-height: calc(100vh - 180px); /* 确保有明确的高度限制 */
      }
      /* 自定义滚动条样式 */
      .result-content::-webkit-scrollbar {
        width: 6px;
      }
      .result-content::-webkit-scrollbar-track {
        background: #333;
        border-radius: 3px;
      }
      .result-content::-webkit-scrollbar-thumb {
        background: #666;
        border-radius: 3px;
      }
      .result-content::-webkit-scrollbar-thumb:hover {
        background: #888;
      }
      /* 移动端实时输出区域 */
      .mobile-result-content {
        max-height: 300px;
      }
      .status-indicator {
        @apply inline-block w-2 h-2 rounded-full mr-2;
      }
      /* 语言参考表样式 */
      .lang-reference {
        @apply bg-white rounded-xl card-shadow p-5;
      }
      .lang-table {
        @apply w-full text-sm border-collapse;
      }
      .lang-table th {
        @apply bg-gray-50 text-left py-2 px-3 font-medium text-gray-600 border-b;
      }
      .lang-table td {
        @apply py-2 px-3 border-b border-gray-100;
      }
      .lang-table tr:last-child td {
        @apply border-0;
      }
      .lang-table tr:nth-child(even) td {
        @apply bg-gray-50;
      }
      /* 筛选框样式 */
      .lang-filter {
        @apply relative mb-4;
      }
      .lang-filter input {
        @apply w-full pl-9 pr-4 py-2 border border-gray-300 rounded-lg input-focus transition-all text-sm;
      }
      .lang-filter i {
        @apply absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400;
      }
      /* 固定定位容器 */
      .fixed-sidebar {
        @apply fixed top-6 bottom-6 w-[30vw]  overflow-hidden;
        max-width: 25vw;
      }
      .fixed-rightbar {
        @apply fixed top-6 bottom-6 right-6 w-[30vw]  overflow-hidden;
        max-width: 25vw;
      }
      /* 主内容区域 */
      .main-content {
        @apply mx-auto w-full max-w-3xl px-4 md:px-6;
      }
      @media (min-width: 1024px) {
        .main-content {
          margin-left: calc(24vw + 2rem);
          margin-right: calc(24vw + 2rem);
          max-width: calc(100% - 48vw - 4rem);
        }
      }
    }
  </style>
</head>

<body class="bg-gray-50 min-h-screen font-sans text-dark p-4 md:p-6">
  <!-- 创建一个专门用于挂载Vue的容器 -->
  <div id="app">
    <!-- 页面标题 -->
    <header class="mb-6 text-center">
      <h1 class="text-[clamp(1.8rem,4vw,2.5rem)] font-bold text-dark mb-2">翻译工具配置中心</h1>
      <p class="text-neutral">配置翻译服务并执行翻译操作</p>
    </header>

    <!-- 左侧：语言编码参考表（固定定位） -->
    <div class="fixed-sidebar left-6 hidden md:block">
      <div class="lang-reference h-full flex flex-col">
        <h2 class="text-lg font-semibold mb-4 flex items-center">
          <i class="fa fa-language text-primary mr-2"></i>语言编码参考
        </h2>

        <!-- 筛选输入框 -->
        <div class="lang-filter">
          <i class="fa fa-search"></i>
          <input type="text" placeholder="搜索语言或编码..." v-model="searchQuery" @input="filterLanguages">
        </div>

        <div class="text-xs text-gray-500 mb-3">
          常用语言编码对照表 (ISO 639-1)
        </div>
        <div class="overflow-y-auto flex-1">
          <table class="lang-table">
            <thead>
              <tr>
                <th>语言</th>
                <th>编码</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="lang in filteredLanguages" :key="lang.code">
                <td>{{ lang.name }}</td>
                <td>{{ lang.code }}</td>
              </tr>
              <tr v-if="filteredLanguages.length === 0">
                <td colspan="2" class="text-center py-4 text-gray-500">
                  没有找到匹配的语言
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="mt-4 text-xs text-gray-500 italic">
          提示：多个语言编码用逗号分隔，如 "en,ja,ko"
        </div>
      </div>
    </div>

    <!-- 右侧：实时结果展示框（固定定位） -->
    <div class="fixed-rightbar right-6 hidden md:block">
      <div class="result-box h-full">
        <div class="p-4 border-b border-gray-200">
          <h2 class="text-lg font-semibold flex items-center">
            <i class="fa fa-terminal text-primary mr-2"></i>实时输出
          </h2>
          <div class="mt-2 flex items-center text-sm">
            <span
              :class="{'status-indicator bg-error': !sseConnected, 'status-indicator bg-success': sseConnected}"></span>
            <span :class="{'text-error': !sseConnected, 'text-success': sseConnected}">
              {{ sseConnected ? '已连接' : '未连接' }}
            </span>
            <button class="ml-auto px-3 py-1 text-xs rounded bg-gray-200 hover:bg-gray-300 transition-colors"
              @click="sseConnected ? disconnectSSE() : connectSSE()">
              {{ sseConnected ? '断开连接' : '连接' }}
            </button>
          </div>
        </div>

        <div class="p-4 flex-1 flex flex-col">
          <!-- 实时输出区域 - 带优化的滚动 -->
          <div class="result-content mb-4" ref="resultContent">
            <div v-for="(message, index) in sseMessages" :key="index" class="mb-1">
              <span class="text-gray-400">[{{ message.timestamp }}]</span>
              <span
                :class="message.type === 'error' ? 'text-error' : message.type === 'success' ? 'text-success' : 'text-primary'">
                {{ message.content }}
              </span>
            </div>
            <div v-if="sseMessages.length === 0" class="text-gray-500 italic">
              等待连接...
            </div>
          </div>

          <div class="flex justify-between items-center">
            <button class="text-xs text-gray-500 hover:text-gray-700" @click="clearMessages()">
              <i class="fa fa-trash-o mr-1"></i>清空
            </button>
            <div class="text-xs text-gray-400">
              共 {{ sseMessages.length }} 条消息
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 中间：表单配置区域（主内容区） -->
    <div class="main-content">
      <main class="bg-white rounded-xl card-shadow p-6 md:p-8">
        <!-- 移动端：语言编码参考表（仅在小屏幕显示） -->
        <div class="md:hidden mb-6">
          <div class="lang-reference">
            <h2 class="text-lg font-semibold mb-4 flex items-center">
              <i class="fa fa-language text-primary mr-2"></i>语言编码参考
            </h2>

            <!-- 筛选输入框 -->
            <div class="lang-filter">
              <i class="fa fa-search"></i>
              <input type="text" placeholder="搜索语言或编码..." v-model="searchQuery" @input="filterLanguages">
            </div>

            <div class="overflow-y-auto max-h-60">
              <table class="lang-table">
                <thead>
                  <tr>
                    <th>语言</th>
                    <th>编码</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="lang in filteredLanguages" :key="lang.code">
                    <td>{{ lang.name }}</td>
                    <td>{{ lang.code }}</td>
                  </tr>
                  <tr v-if="filteredLanguages.length === 0">
                    <td colspan="2" class="text-center py-4 text-gray-500">
                      没有找到匹配的语言
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <!-- 信息提示框 (根据数据显示/隐藏) -->
        <div v-if="showFormData" class="info-box">
          <h3 class="font-medium text-primary mb-2 flex items-center">
            <i class="fa fa-info-circle mr-2"></i>收集的表单信息
          </h3>
          <pre class="bg-gray-100 p-3 rounded overflow-x-auto text-gray-700">{{ displayFormData }}</pre>
        </div>

        <!-- 云服务配置区域 -->
        <section class="mb-10">
          <h2 class="text-xl font-semibold mb-6 pb-2 border-b border-gray-200 flex items-center">
            <i class="fa fa-cogs text-primary mr-2"></i>云服务配置
          </h2>

          <!-- 阿里云翻译配置 -->
          <div class="mb-8 p-5 bg-blue-50 rounded-lg">
            <h3 class="text-lg font-medium mb-4 text-primary flex items-center">
              <i class="fa fa-cloud mr-2"></i>阿里云翻译配置
            </h3>
            <div class="grid md:grid-cols-2 gap-4">
              <div>
                <label for="ali-accessKeyId" class="block text-sm font-medium text-gray-700 mb-1">Access Key
                  ID</label>
                <input type="text" id="ali-accessKeyId"
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all"
                  placeholder="输入阿里云Access Key ID" v-model="aliyun.accessKeyId">
              </div>
              <div>
                <label for="ali-accessKeySecret" class="block text-sm font-medium text-gray-700 mb-1">Access Key
                  Secret</label>
                <input type="password" id="ali-accessKeySecret"
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all"
                  placeholder="输入阿里云Access Key Secret" v-model="aliyun.accessKeySecret">
              </div>
            </div>
          </div>

          <!-- 百度云翻译配置 -->
          <div class="mb-6 p-5 bg-green-50 rounded-lg">
            <h3 class="text-lg font-medium mb-4 text-green-600 flex items-center">
              <i class="fa fa-cloud mr-2"></i>百度云翻译配置
            </h3>
            <div class="grid md:grid-cols-2 gap-4">
              <div>
                <label for="baidu-appid" class="block text-sm font-medium text-gray-700 mb-1">Access Key
                  ID</label>
                <input type="text" id="baidu-appid"
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all"
                  placeholder="输入百度云Access Key ID" v-model="baidu.appid">
              </div>
              <div>
                <label for="baidu-secret" class="block text-sm font-medium text-gray-700 mb-1">Access Key
                  Secret</label>
                <input type="password" id="baidu-secret"
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all"
                  placeholder="输入百度云Access Key Secret" v-model="baidu.secret">
              </div>
            </div>
          </div>

          <!-- 翻译引擎选择 -->
          <div class="p-5 bg-gray-50 rounded-lg">
            <h3 class="text-lg font-medium mb-4 flex items-center">
              <i class="fa fa-exchange text-neutral mr-2"></i>翻译引擎选择
            </h3>
            <div class="space-y-4">
              <div>
                <label for="translate-engine" class="block text-sm font-medium text-gray-700 mb-1">选择翻译引擎(阿里更准确)</label>
                <select id="translate-engine"
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all appearance-none bg-white"
                  v-model="translateEngine" @change="toggleProfessionalMode">
                  <option value="baidu">百度云翻译</option>
                  <option value="aliyun">阿里云翻译</option>
                </select>
              </div>

              <!-- 专业模式开关 (根据数据显示/隐藏) -->
              <div v-if="showProfessionalModeContainer" class="transition-all duration-300">
                <div class="flex items-center justify-between">
                  <label class="text-sm font-medium text-gray-700">是否启用专业模式</label>
                  <!-- 开关按钮 -->
                  <div class="relative inline-block w-12 h-6">
                    <input type="checkbox" id="professional-mode"
                      class="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 appearance-none cursor-pointer transition-all duration-300 ease-in-out"
                      v-model="professionalMode" @change="toggleSceneSelection">
                    <label for="professional-mode"
                      class="toggle-label block overflow-hidden h-6 rounded-full bg-gray-300 cursor-pointer transition-all duration-300 ease-in-out"
                      :class="{ 'bg-primary': professionalMode }"></label>
                  </div>
                </div>

                <!-- 场景选择下拉框 (根据数据显示/隐藏) -->
                <div v-if="showSceneSelectionContainer" class="mt-4 transition-all duration-300"
                  :style="{ opacity: showSceneSelectionContainer ? 1 : 0, transform: showSceneSelectionContainer ? 'translateY(0)' : 'translateY(-10px)' }">
                  <label for="scene" class="block text-sm font-medium text-gray-700 mb-1">选择翻译场景</label>
                  <select id="scene"
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all appearance-none bg-white"
                    v-model="scene">
                    <option value="title">商品标题（title）</option>
                    <option value="description">商品描述（description）</option>
                    <option value="communication">商品沟通（communication）</option>
                    <option value="medical">医疗（medical）</option>
                    <option value="social">社交（social）</option>
                    <option value="finance">金融（finance）</option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        </section>

        <!-- 操作标签页 -->
        <section>
          <h2 class="text-xl font-semibold mb-6 pb-2 border-b border-gray-200 flex items-center">
            <i class="fa fa-tasks text-primary mr-2"></i>翻译操作
          </h2>

          <!-- 标签页导航 -->
          <div class="border-b border-gray-200 mb-4">
            <ul class="flex flex-wrap -mb-px text-sm font-medium text-center" id="tab-tabs" role="tablist">
              <li class="mr-2" role="presentation">
                <button id="vue-translate-tab" data-tabs-target="#vue-translate" type="button"
                  class="inline-block p-4 border-b-2 rounded-t-lg" role="tab" @click="activeTab = 'vue-translate'"
                  :class="{ 'tab-active': activeTab === 'vue-translate' }">
                  <i class="fa fa-code mr-1"></i>vue翻译提取
                </button>
              </li>
              <li class="mr-2" role="presentation">
                <button id="translation-patch-tab" data-tabs-target="#translation-patch" type="button"
                  class="inline-block p-4 border-b-2 border-transparent rounded-t-lg hover:text-gray-600 hover:border-gray-300"
                  role="tab" @click="activeTab = 'translation-patch'"
                  :class="{ 'tab-active': activeTab === 'translation-patch' }">
                  <i class="fa fa-file-text-o mr-1"></i>翻译补丁
                </button>
              </li>
              <li class="mr-2" role="presentation">
                <button id="checkKeys-tab" data-tabs-target="#checkKeys" type="button"
                  class="inline-block p-4 border-b-2 border-transparent rounded-t-lg hover:text-gray-600 hover:border-gray-300"
                  role="tab" @click="activeTab = 'checkKeys'" :class="{ 'tab-active': activeTab === 'checkKeys' }">
                  <i class="fa fa-file-text-o mr-1"></i>检查多余key
                </button>
              </li>
            </ul>
          </div>

          <!-- 标签页内容 -->
          <div id="tab-contents">
            <!-- Vue翻译提取 -->
            <div id="vue-translate" class="tab-content" v-if="activeTab === 'vue-translate'">
              <p class="text-error">
                <i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
                此操作会自动提取vue文件中中文替换，替换可能不准确注意备份
              </p>
              <div class="space-y-4 p-4 bg-gray-50 rounded-lg">
                <div>
                  <label for="vue-scan-path" class="block text-sm font-medium text-gray-700 mb-1">扫描目录</label>
                  <input type="text" id="vue-scan-path"
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all"
                    placeholder="例如: src/views" v-model="vueTranslate.scanPath">
                  <p class="text-warning text-sm">建议将文件放置此目录运行</p>
                </div>
                <div>
                  <label for="translate-lang" class="block text-sm font-medium text-gray-700 mb-1">需要翻译的语言</label>
                  <input type="text" id="translate-lang"
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all"
                    placeholder="例如: en, ja, ko" v-model="vueTranslate.toTranslateLang">
                </div>
              </div>
            </div>

            <!-- 翻译补丁 -->
            <div id="translation-patch" class="tab-content" v-if="activeTab === 'translation-patch'">
              <div class="space-y-4 p-4 bg-gray-50 rounded-lg">
                <div>
                  <label for="patch-scan-path" class="block text-sm font-medium text-gray-700 mb-1">扫描目录</label>
                  <input type="text" id="patch-scan-path"
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all"
                    placeholder="例如: src/locales" v-model="translationPatch.scanPath">
                </div>
                <div>
                  <label for="source-lang" class="block text-sm font-medium text-gray-700 mb-1">源语言</label>
                  <input type="text" id="source-lang"
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all"
                    placeholder="例如: zh-CN" v-model="translationPatch.source">
                </div>
                <!-- 文件类型选择 - 单选下拉框 -->
                <div>
                  <label for="file-type" class="block text-sm font-medium text-gray-700 mb-1">文件类型</label>
                  <select id="file-type"
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all appearance-none bg-white"
                    v-model="translationPatch.fileType">
                    <option value="js">JavaScript (.js)</option>
                    <option value="json">JSON (.json)</option>
                  </select>
                  <p class="mt-1 text-xs text-gray-500">选择需要处理的文件类型</p>
                </div>
              </div>
            </div>
            <!-- 检查多余key -->
            <div id="checkKeys" class="tab-content" v-if="activeTab === 'checkKeys'">
              <div class="space-y-4 p-4 bg-gray-50 rounded-lg">
                <div>
                  <label for="checkKeys-scan-path" class="block text-sm font-medium text-gray-700 mb-1">扫描目录</label>
                  <input type="text" id="checkKeys-scan-path"
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all"
                    placeholder="例如: src/locales" v-model="checkKeys.scanPath">
                </div>
                <!-- 新增：两个功能按钮 -->
                <div class="flex flex-wrap gap-3 mt-2">
                  <!-- 扫描多余key按钮 -->
                  <button
                    class="px-4 py-2 bg-primary hover:bg-primary/90 text-white font-medium rounded-lg transition-all focus:ring-4 focus:ring-primary/30 focus:outline-none"
                    @click="scanExtraKeys" :disabled="isScanningKeys || isSubmitting">
                    <i v-if="!isScanningKeys" class="fa fa-search mr-1"></i>
                    <i v-if="isScanningKeys" class="fa fa-spinner fa-spin mr-1"></i>
                    <span v-if="!isScanningKeys">扫描多余的key</span>
                    <span v-if="isScanningKeys">扫描中...</span>
                  </button>
                  <!-- 一键去除多余key按钮 -->
                  <button
                    class="px-4 py-2 bg-warning hover:bg-warning/90 text-white font-medium rounded-lg transition-all focus:ring-4 focus:ring-warning/30 focus:outline-none"
                    @click="removeExtraKeys" :disabled="isRemovingKeys || isScanningKeys || isSubmitting">
                    <i v-if="!isRemovingKeys" class="fa fa-trash mr-1"></i>
                    <i v-if="isRemovingKeys" class="fa fa-spinner fa-spin mr-1"></i>
                    <span v-if="!isRemovingKeys">一键去除多余的key</span>
                    <span v-if="isRemovingKeys">删除中...</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </section>

        <!-- 提交按钮 -->
        <div class="mt-10 text-center" v-if="activeTab !== 'checkKeys'">
          <button id="submit-btn"
            class="px-8 py-3 bg-primary hover:bg-primary/90 text-white font-medium rounded-lg transition-all transform hover:scale-[1.02] focus:ring-4 focus:ring-primary/30 focus:outline-none"
            @click="submitForm" :disabled="isSubmitting">
            <i v-if="!isSubmitting" class="fa fa-play-circle mr-2"></i>
            <i v-if="isSubmitting" class="fa fa-spinner fa-spin mr-2"></i>
            <span v-if="!isSubmitting && !isSubmitted">执行翻译操作</span>
            <span v-if="isSubmitting">处理中...</span>
            <span v-if="!isSubmitting && isSubmitted">操作完成</span>
          </button>
        </div>

        <!-- 移动端：实时输出区域（仅在小屏幕显示） -->
        <div class="mt-6 md:hidden">
          <div class="result-box">
            <div class="p-4 border-b border-gray-200">
              <h2 class="text-lg font-semibold flex items-center">
                <i class="fa fa-terminal text-primary mr-2"></i>实时输出
              </h2>
              <div class="mt-2 flex items-center text-sm">
                <span
                  :class="{'status-indicator bg-error': !sseConnected, 'status-indicator bg-success': sseConnected}"></span>
                <span :class="{'text-error': !sseConnected, 'text-success': sseConnected}">
                  {{ sseConnected ? '已连接' : '未连接' }}
                </span>
                <button class="ml-auto px-3 py-1 text-xs rounded bg-gray-200 hover:bg-gray-300 transition-colors"
                  @click="sseConnected ? disconnectSSE() : connectSSE()">
                  {{ sseConnected ? '断开连接' : '连接' }}
                </button>
              </div>
            </div>

            <div class="p-4 flex-1 flex flex-col">
              <!-- 移动端实时输出区域 - 带滚动 -->
              <div class="result-content mobile-result-content mb-4" ref="mobileResultContent">
                <div v-for="(message, index) in sseMessages" :key="index" class="mb-1">
                  <span class="text-gray-400">[{{ message.timestamp }}]</span>
                  <span
                    :class="message.type === 'error' ? 'text-error' : message.type === 'success' ? 'text-success' : 'text-primary'">
                    {{ message.content }}
                  </span>
                </div>
                <div v-if="sseMessages.length === 0" class="text-gray-500 italic">
                  等待连接...
                </div>
              </div>

              <div class="flex justify-between items-center">
                <button class="text-xs text-gray-500 hover:text-gray-700" @click="clearMessages()">
                  <i class="fa fa-trash-o mr-1"></i>清空
                </button>
                <div class="text-xs text-gray-400">
                  共 {{ sseMessages.length }} 条消息
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>

    <!-- 页脚 -->
    <footer class="mt-10 text-center text-neutral text-sm main-content">
      <p>翻译工具配置中心 © 2023</p>
    </footer>
  </div>

  <!-- Vue 实例 -->
  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          // 语言编码数据
          originalLanguages: {},
          searchQuery: '',
          filteredLanguages: [],

          // 云服务配置
          aliyun: {
            accessKeyId: 'LTAI5t8fuC6xD1n4FffHtUbq',
            accessKeySecret: 'nXK68wjL26MAKstA4k5VIcHTqp68Cg'
          },
          baidu: {
            appid: '20210930000960868',
            secret: 'LGM72ZezVRutwJcJ5OWz',
          },
          // 翻译引擎设置
          translateEngine: 'aliyun',
          professionalMode: false,
          scene: 'title',
          // 标签页状态
          activeTab: 'translation-patch',
          // 标签页数据
          vueTranslate: {
            scanPath: './source',
            toTranslateLang: 'en,fil,de'
          },
          translationPatch: {
            scanPath: './dist/lang',
            source: 'en',
            patch: true,
            // 文件类型为单选
            fileType: 'json'
          },
          checkKeys: {
            scanPath: 'F:\lq\sz\game-center-black-h5\src',
          },
          isScanningKeys: false,  // 扫描按钮禁用状态
          isRemovingKeys: false,   // 去除按钮禁用状态
          // 表单提交状态
          isSubmitting: false,
          isSubmitted: false,
          showFormData: false,
          formData: null,

          // SSE相关状态
          sseConnected: false,
          sseSource: null,
          sseMessages: []
        }
      },
      computed: {
        // 计算属性：是否显示专业模式容器
        showProfessionalModeContainer() {
          return this.translateEngine === 'aliyun';
        },
        languages() {
          return this.originalLanguages[this.translateEngine] || []
        },
        // 计算属性：是否显示场景选择容器
        showSceneSelectionContainer() {
          return this.showProfessionalModeContainer && this.professionalMode;
        },
        // 格式化表单数据用于展示
        displayFormData() {
          return JSON.stringify(this.formData, null, 2);
        }
      },

      methods: {
        /**
   * 扫描多余的key：发送请求到后端，获取多余key列表
   */
        scanExtraKeys() {
          // 1. 校验扫描目录是否填写
          if (!this.checkKeys.scanPath.trim()) {
            this.addSSEMessage("请先填写「扫描目录」（如 src/locales）", "error");
            return;
          }

          // 2. 初始化状态和日志
          this.isScanningKeys = true;
          this.addSSEMessage(`开始扫描目录：${this.checkKeys.scanPath}`, "info");

          // 3. 发送请求到后端（需与后端接口匹配，此处为示例路径）
          fetch("/scan-extra-keys", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ scanPath: this.checkKeys.scanPath })
          })
            .then(res => {
              if (!res.ok) throw new Error(`HTTP错误：${res.status}`);
              return res.json();
            })
            .then(data => {
              this.isScanningKeys = false;
              if (data.success) {
                this.addSSEMessage(`扫描完成！共发现 ${data.extraKeysCount || 0} 个多余key`, "success");
                // 若后端返回具体key列表，可追加日志
                if (data.extraKeys && data.extraKeys.length) {
                  this.addSSEMessage(`多余key列表：${JSON.stringify(data.extraKeys)}`, "info");
                }
              } else {
                this.addSSEMessage(`扫描失败：${data.message || "未知错误"}`, "error");
              }
            })
            .catch(err => {
              this.isScanningKeys = false;
              this.addSSEMessage(`扫描请求异常：${err.message}`, "error");
              console.error("扫描多余key错误：", err);
            });
        },

        /**
         * 一键去除多余的key：发送删除请求，需二次确认
         */
        removeExtraKeys() {
          // 1. 二次确认（防止误操作）
          const confirmDelete = window.confirm(
            "确定要删除所有多余的key吗？此操作不可逆，请确保已备份文件！"
          );
          if (!confirmDelete) return;

          // 2. 校验扫描目录是否填写
          if (!this.checkKeys.scanPath.trim()) {
            this.addSSEMessage("请先填写「扫描目录」（如 src/locales）", "error");
            return;
          }

          // 3. 初始化状态和日志
          this.isRemovingKeys = true;
          this.addSSEMessage(`开始删除目录 ${this.checkKeys.scanPath} 中的多余key`, "warning");

          // 4. 发送删除请求到后端（需与后端接口匹配，此处为示例路径）
          fetch("/remove-extra-keys", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ scanPath: this.checkKeys.scanPath })
          })
            .then(res => {
              if (!res.ok) throw new Error(`HTTP错误：${res.status}`);
              return res.json();
            })
            .then(data => {
              this.isRemovingKeys = false;
              if (data.success) {
                this.addSSEMessage(`删除完成！共移除 ${data.removedCount || 0} 个多余key`, "success");
              } else {
                this.addSSEMessage(`删除失败：${data.message || "未知错误"}`, "error");
              }
            })
            .catch(err => {
              this.isRemovingKeys = false;
              this.addSSEMessage(`删除请求异常：${err.message}`, "error");
              console.error("删除多余key错误：", err);
            });
        },
        // 筛选语言
        filterLanguages() {
          if (!this.searchQuery) {
            this.filteredLanguages = [...this.languages];
            return;
          }

          const query = this.searchQuery.toLowerCase();
          this.filteredLanguages = this.languages.filter(lang =>
            lang.name.toLowerCase().includes(query) ||
            lang.code.toLowerCase().includes(query)
          );
        },

        // 切换专业模式
        toggleProfessionalMode() {
          if (this.translateEngine !== 'aliyun') {
            this.professionalMode = false;
          }
          this.filteredLanguages = [...this.languages]
        },
        // 切换场景选择
        toggleSceneSelection() {
          // 空实现，由v-model自动处理
        },
        // 收集表单数据
        collectFormData() {
          return {
            aliyun: {
              region: 'cn-hangzhou',
              endpoint: 'mt.cn-hangzhou.aliyuncs.com',
              apiVersion: '2018-10-12',
              ...this.aliyun,
            },
            baidu: { ...this.baidu },
            autoReWriter: true,
            engine: this.translateEngine,
            activeTab: this.activeTab,
            toTranslateLang: this.vueTranslate.toTranslateLang.split(','),
            scanPath: this.vueTranslate.scanPath,
            professionalMode: this.professionalMode,
            scene: this.scene,
            patchTranslation: { ...this.translationPatch },

          };
        },
        // 提交表单
        submitForm() {
          this.formData = this.collectFormData();
          // this.showFormData = true;

          // 滚动到表单数据展示区域
          // setTimeout(() => {
          //   const infoBox = document.querySelector('.info-box');
          //   if (infoBox) {
          //     infoBox.scrollIntoView({ behavior: 'smooth', block: 'start' });
          //   }
          // }, 100);

          // 提交时自动连接SSE
          if (!this.sseConnected) {
            this.connectSSE();
          }

          // 模拟提交过程
          this.isSubmitting = true;
          this.isSubmitted = false;
          fetch('/start', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(this.formData)
          }).then(response => response.json()).then(data => {
            this.isSubmitting = false;
            this.isSubmitted = true;

          });

        },

        // SSE连接方法
        connectSSE() {
          // 关闭已存在的连接
          if (this.sseSource) {
            this.sseSource.close();
          }

          try {
            // 创建SSE连接（实际项目中替换为真实的后端接口）
            this.sseSource = new EventSource('/sse');

            // 连接成功
            this.sseSource.onopen = (event) => {
              this.sseConnected = true;
              this.addSSEMessage('SSE连接已建立', 'info');
              console.log('SSE连接已建立', event);
            };

            // 接收消息
            this.sseSource.onmessage = (event) => {
              try {
                let data = ''
                if (typeof event.data === 'object') {
                  data = event.data;
                } else {
                  data = JSON.parse(event.data);
                }
                // 尝试解析JSON格式的消息
                this.addSSEMessage(data.content, data.type || 'info');
              } catch (e) {
                // 如果不是JSON格式，直接显示文本
                this.addSSEMessage(event.data, 'info');
              }
            };

            // 连接错误
            this.sseSource.onerror = (error) => {
              this.addSSEMessage(`SSE连接错误: ${error.message}`, 'error');
              console.error('SSE连接错误', error);

              // 自动重连
              if (this.sseConnected) {
                this.sseConnected = false;
                setTimeout(() => {
                  this.addSSEMessage('尝试重新连接...', 'warning');
                  this.connectSSE();
                }, 3000);
              }

              this.sseSource.close();
            };

          } catch (error) {
            this.addSSEMessage(`无法建立SSE连接: ${error.message}`, 'error');
            console.error('SSE连接失败', error);
          }
        },

        // 断开SSE连接
        disconnectSSE() {
          if (this.sseSource) {
            this.sseSource.close();
            this.sseSource = null;
          }
          this.sseConnected = false;
          this.addSSEMessage('SSE连接已断开', 'info');
        },

        // 添加SSE消息 - 优化滚动行为
        addSSEMessage(content, type = 'info') {
          if (content === '') return;
          const timestamp = new Date().toLocaleTimeString();
          this.sseMessages.push({ timestamp, content, type });

          // 保持滚动到底部（桌面端和移动端）
          this.$nextTick(() => {
            // 桌面端实时输出区域
            const resultContent = this.$refs.resultContent;
            if (resultContent) {
              // 只有当用户没有手动滚动时，才自动滚动到底部
              const isScrolledToBottom = resultContent.scrollTop + resultContent.clientHeight >= resultContent.scrollHeight - 10;
              if (isScrolledToBottom) {
                resultContent.scrollTop = resultContent.scrollHeight;
              }
            }

            // 移动端实时输出区域
            const mobileResultContent = this.$refs.mobileResultContent;
            if (mobileResultContent) {
              const isMobileScrolledToBottom = mobileResultContent.scrollTop + mobileResultContent.clientHeight >= mobileResultContent.scrollHeight - 10;
              if (isMobileScrolledToBottom) {
                mobileResultContent.scrollTop = mobileResultContent.scrollHeight;
              }
            }
          });

          // 限制消息数量，防止内存溢出
          if (this.sseMessages.length > 1000) {
            this.sseMessages.shift();
          }
        },

        // 清空消息
        clearMessages() {
          this.sseMessages = [];
        }
      },
      watch: {
        professionalMode(newVal) {
          if (newVal) {
            const sceneContainer = document.getElementById('scene-selection-container');
            if (sceneContainer) {
              sceneContainer.style.opacity = "0";
              sceneContainer.style.transform = "translateY(-10px)";

              setTimeout(() => {
                sceneContainer.style.opacity = "1";
                sceneContainer.style.transform = "translateY(0)";
              }, 10);
            }
          }
        }
      },
      mounted() {
        // 初始化开关样式
        const professionalModeSwitch = document.getElementById('professional-mode');
        if (professionalModeSwitch) {
          this.$watch('professionalMode', (newVal) => {
            if (newVal) {
              professionalModeSwitch.classList.add('right-0', 'border-primary');
              professionalModeSwitch.classList.remove('left-0', 'border-gray-300');
            } else {
              professionalModeSwitch.classList.remove('right-0', 'border-primary');
              professionalModeSwitch.classList.add('left-0', 'border-gray-300');
            }
          });
        }
        fetch('/getLangCode').then(res => res.json()).then(res => {
          this.originalLanguages = res.data;
          this.$nextTick(() => {
            this.filteredLanguages = [...this.languages];
          })
        });
      },
      beforeDestroy() {
        // 组件销毁时断开SSE连接
        this.disconnectSSE();
      }
    });
  </script>
</body>

</html>